package com.example.book.controller;


import com.example.book.constant.Constants;
import com.example.book.enums.BookStatusEnum;
import com.example.book.model.BookInfo;
import com.example.book.model.PageResponse;
import com.example.book.model.PageRequest;
import com.example.book.model.Result;
import com.example.book.service.BookService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    //从Spring容器里取出来
    @Autowired
    private BookService bookService;

    @RequestMapping("/addBook")
    public String addBook(BookInfo bookInfo) {
        log.info("添加图书:{}", bookInfo);
        //参数校验
        if (!StringUtils.hasLength(bookInfo.getBookName())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || !StringUtils.hasLength(bookInfo.getPublish())
                || bookInfo.getCount() == null
                || bookInfo.getPrice() == null
                || bookInfo.getStatus() == null
        ) {
            return "输入参数不合法，请检查入参";
        }
        //插入数据
        try {
            Integer result = bookService.addBook(bookInfo);
            if (result == 1) {
                return "";
            }
        } catch (Exception e) {
            log.error("添加图书失败,e:{}", e);
            //把堆栈也一起打印了
            e.printStackTrace();
        }
        return "数据插入失败，请联系管理员";

    }

    //查询图书信息（翻页使用)
    @RequestMapping("/getListByPage")
    public Result<PageResponse<BookInfo>> getListByPage(PageRequest pageRequest, HttpServletRequest request) {
        log.info("获取图书列表，pageRequest：{}", pageRequest);
        //已加上默认值，不用校验参数
        //字符串比较不能用==
        //if(session.getAttribute("username")==""){
        //if("".equals(session.getAttribute("username"))){
        HttpSession session= request.getSession(false);
        if (session==null||session.getAttribute(Constants.SESSION_USER_KEY) == null ||
                !StringUtils.hasLength((String) session.getAttribute(Constants.SESSION_USER_KEY))) {
            //返回空的话，证明用户未登录
            return Result.unlogin();
        }

        PageResponse<BookInfo> bookInfoPageResponse = new PageResponse<>();
        try {
            bookInfoPageResponse = bookService.getListByPage(pageRequest);
        } catch (Exception e) {
            log.error("获取图书列表失败");
            return Result.fail();
        }
        return Result.success(bookInfoPageResponse);

    }

    //修改图书
    //进入修改页面, 需要显示当前图书的信息
    @RequestMapping("/queryBookById")
    public BookInfo queryBookById(Integer bookId) {
        log.info("获取图书信息，bookId:" + bookId);
        //参数校验，不能为null,不能<=0
        //加try，catch
        return bookService.queryBookById(bookId);

    }

    //点击修改按钮, 修改图书图书的信息
    @RequestMapping("/updateBook")
    public String updateBook(BookInfo bookInfo) {
        log.info("更新图书,bookInfo:{}", bookInfo);
        try {
            Integer result = bookService.updateBook(bookInfo);
            if (result > 0) {
                return "";
            }
            return "更新图书失败";
        } catch (Exception e) {
            log.error("更新图书失败，e:", e);
            return "数据库更新失败";

        }

    }

    //删除操作（逻辑删除）
    @RequestMapping("/deleteBook")
    public String deleteBook(Integer bookId) {
        log.info("删除图书,bookId:{}", bookId);
        try {
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(bookId);
            bookInfo.setStatus(BookStatusEnum.DELETED.getCode());
            Integer result = bookService.updateBook(bookInfo);
            if (result > 0) {
                return "";
            }
            return "图书删除失败";
        } catch (Exception e) {
            log.error("删除图书失败，e:", e);
            return "数据库更新失败";

        }

    }

    //批量删除
    @RequestMapping("/batchDeleteBook")
    //List<>需要绑定参数
    public Boolean batchDeleteBook(@RequestParam List<Integer> ids) {
        log.info("批量删除图书：ids:{}", ids);
        try {
            //执行SQL
            bookService.batchDeleteBook(ids);
            return true;
        } catch (Exception e) {
            log.error("批量删除图书失败,ids:{}", ids);
        }
        return false;

    }


}
